<template>
    <div>
        <el-form-item label="自动宽度">
            <el-switch v-model="optionModel.autoWidth"> </el-switch>
        </el-form-item>
        <el-form-item label="最大高度">
            <el-input v-model="optionModel.maxHeight"> </el-input>
        </el-form-item>
        <el-form-item label="显示行号">
            <el-switch v-model="optionModel.showIndex"> </el-switch>
        </el-form-item>
        <el-form-item label="允许新增">
            <el-switch v-model="optionModel.enableAdd"> </el-switch>
        </el-form-item>
        <el-form-item label="允许删除">
            <el-switch v-model="optionModel.enableDelete"> </el-switch>
        </el-form-item>
        <el-form-item label="总是显示滚动条">
            <el-switch v-model="optionModel.scrollbarAlways"> </el-switch>
        </el-form-item>
        <el-form-item label="显示合计">
            <el-switch v-model="optionModel.showSummary"> </el-switch>
        </el-form-item>
        <template v-if="optionModel.showSummary">
            <el-form-item label="合计包含分页">
                <el-switch v-model="optionModel.inPagination"> </el-switch>
            </el-form-item>
        </template>
        <!-- 分页信息 -->
        <el-form-item label="显示分页">
            <el-switch v-model="optionModel.showPagination"> </el-switch>
        </el-form-item>
        <template v-if="optionModel.showPagination">
            <el-form-item label="每页大小">
                <el-input-number
                    v-model="optionModel.pagination.pageSize"
                    :step="1"
                    :controls="true"
                    controls-position="both">
                </el-input-number>
            </el-form-item>
        </template>

        <!--
        <el-form-item label="是否开启校验">
            <el-switch
                v-model="optionModel.enableValidate"
                :active-value="true"
                :inactive-value="false"
                @change="">
            </el-switch>
        </el-form-item>
        -->
        <!-- 校验规则 -->
        <el-form-item label="校验规则" v-if="optionModel.enableValidate">
            <el-button type="primary" plain round @click="openValidateEdit">{{
                i18nt("designer.setting.editAction")
            }}</el-button>
        </el-form-item>
        <div
            v-if="validateDialogVisible"
            v-drag="[
                '.drag-dialog.el-dialog',
                '.drag-dialog .el-dialog__header',
            ]">
            <el-dialog
                title="编辑校验规则"
                v-model="validateDialogVisible"
                :show-close="true"
                class="drag-dialog small-padding-dialog"
                append-to-body
                :close-on-click-modal="false"
                :close-on-press-escape="false"
                :destroy-on-close="true"
                width="700">
                <template v-for="(item, index) in validateArr">
                    <div class="validate">
                        <div class="title">
                            <div># {{ index + 1 }}</div>
                            <el-popconfirm
                                :title="i18nt('designer.setting.confirmDelete')"
                                @confirm="deleteValidate(index)">
                                <template #reference>
                                    <el-icon style="cursor: pointer">
                                        <Delete />
                                    </el-icon>
                                </template>
                            </el-popconfirm>
                        </div>
                        <div class="body">
                            <el-form
                                :model="item"
                                :ref="'form' + index"
                                label-position="left"
                                :rules="rules"
                                label-width="120px"
                                :inline="false">
                                <el-form-item label="列字段" prop="columnName">
                                    <el-select v-model="item.columnName">
                                        <el-option
                                            v-for="item in columnOptions"
                                            :key="item.value"
                                            :label="item.label"
                                            :value="item.value">
                                        </el-option>
                                    </el-select>
                                </el-form-item>
                                <el-form-item label="校验类型" prop="rule">
                                    <el-select v-model="item.rule">
                                        <el-option
                                            v-for="item in ruleOptions"
                                            :key="item.value"
                                            :label="item.label"
                                            :value="item.value">
                                        </el-option>
                                    </el-select>
                                </el-form-item>
                                <el-form-item
                                    :label="
                                        i18nt('designer.setting.targetField')
                                    "
                                    prop="validateField">
                                    <el-cascader
                                        style="width: 100%"
                                        v-model="item.validateField"
                                        :options="nodeTreeData"
                                        :props="cascaderProps" />
                                </el-form-item>
                                <el-form-item label="失败消息">
                                    <el-input
                                        v-model="item.errMsg"
                                        placeholder="可输入自定义校验信息"></el-input>
                                </el-form-item>
                            </el-form>
                        </div>
                    </div>
                </template>
                <el-button
                    type="primary"
                    style="margin-top: 10px"
                    @click="addValidate"
                    >新增校验</el-button
                >

                <template #footer>
                    <div class="dialog-footer">
                        <el-button
                            size="default"
                            type="primary"
                            @click="saveValidateData"
                            >{{ i18nt("designer.hint.confirm") }}</el-button
                        >
                        <el-button
                            size="default"
                            @click="validateDialogVisible = false"
                            >{{ i18nt("designer.hint.cancel") }}</el-button
                        >
                    </div>
                </template>
            </el-dialog>
        </div>
    </div>
</template>

<script>
import i18n from "@/utils/i18n";
import {
  buildWidget,
  getWidgetOptions,
} from "@/components/action-editor/actionUtil";
import {deepClone} from "@/utils/util";

export default {
  name: "table-sub-form-autoWidth-editor",
  mixins: [i18n],
  props: {
    designer: Object,
    selectedWidget: Object,
    optionModel: Object,
  },
  data() {
    return {
      validateDialogVisible: false,
      validateArr: [],
      validateData: {
        //	enable:true,
        columnName: "", //哪个列的合计进行校验。
        rule: "", //比较规则：只能是 > >= < <=  ==
        validateField: "", //需要比较的字段，只能是 输入框或者是其他表格子表单,而且不能夸窗口
        errMsg: "", //失败消息
      },
      ruleOptions: [
        {
          label: "大于",
          value: ">",
        },
        {
          label: "大于等于",
          value: ">=",
        },
        {
          label: "等于",
          value: "==",
        },
        {
          label: "小于",
          value: "<",
        },
        {
          label: "小于等于",
          value: "<=",
        },
      ],
      columnOptions: [],
      nodeTreeData: [], //目标字段
      cascaderProps: {
        label: "desc",
        value: "id",
        multiple: false,
        checkStrictly: false,
        showAllLevels: false,
      },
      needFieldType: ["input", "number", "inputNumber", "table-sub-form"], //允许选择的类型
      rules: {
        columnName: [
          {required: true, message: "请选择【列字段】"},
        ],
        rule: [{required: true, message: "请选择【校验类型】"}],
        validateField: [
          {required: true, message: "请选择【目标字段】"},
        ],
      },
    };
  },
  mounted() {
  },
  methods: {
    deleteValidate(index) {
      this.validateArr.splice(index, 1);
    },
    addValidate() {
      this.validateArr.push(deepClone(this.validateData));
    },
    openValidateEdit() {
      this.nodeTreeData = [];
      this.columnOptions = [];

      this.designer.widgetList.forEach((wItem) => {
        this.buildTreeNodeOfWidget(wItem, this.nodeTreeData);
      });
      console.log("nodeTreeData", this.nodeTreeData)
      this.selectedWidget.widgetList.forEach((col) => {
        this.columnOptions.push({
          label: col.options.label,
          value: col.options.name,
        });
      });

      if (this.optionModel.validateArr) {
        this.validateArr = deepClone(
            this.optionModel.validateArr
        );
      }
      this.validateDialogVisible = true;
    },
    async saveValidateData() {
      if (this.validateArr && this.validateArr.length > 0) {
        const validFlag = await this.validateForm();
        if (validFlag) {
          this.optionModel.validateArr = deepClone(this.validateArr);
          this.validateDialogVisible = false;
        }
      } else {
        this.$message.warning("至少添加一个校验规则");
      }

    },
    validateForm() {
      return new Promise(async (resolve, reject) => {
        let validFlags = [];
        const keys = Object.keys(this.$refs);
        for (let i = 0; i < keys.length; i++) {
          if (this.$refs[keys[i]].length > 0) {
            try {
              const rel = await this.$refs[keys[i]][0].validateField();
              validFlags.push(true);
            } catch (e) {
              validFlags.push(false);
            }
          }

        }
        if (validFlags.length > 0) {
          if (validFlags.includes(false)) {
            resolve(false);
          } else {
            resolve(true);
          }
        } else {
          resolve(false);
        }

      });
    },
    buildTreeNodeOfWidget(widget, treeNode, isField = false) {
      const curNode = getWidgetOptions(widget);
      //widget.options.name != this.optionModel.name &&
      if (
          (this.needFieldType.includes(widget.type)) ||
          (widget.category &&
              widget.options.name != this.optionModel.name &&
              widget.widgetList &&
              widget.widgetList.length > 0) ||
          (widget.rows && widget.rows.length > 0) ||
          (widget.cols && widget.cols.length > 0)
      ) {
        treeNode.push(curNode);
      }

      buildWidget(widget, curNode, isField);
    },
  },
};
</script>

<style lang="scss">
    .validate {
        .title {
            display: flex;
            justify-content: space-between;
            background: #f1f1f1;
            padding: 5px;
        }
        .body {
            padding: 5px;
        }
    }
</style>
